<template>
  <div>
    <el-autocomplete
      v-model="productName"
      v-loading="loading"
      class="inline-input"
      :fetch-suggestions="selectProductList"
      :disabled="disabled"
      placeholder="请输入产品名称"
      style="width: 100%"
      clearable
      @select="handleSelectProduct"
    >
      <template slot-scope="{ item }">
        <div>{{ item.productName }}</div>
      </template>
      <el-button
        slot="append"
        icon="el-icon-search"
        :disabled="disabled"
        @click="openProductDialog"
      />
    </el-autocomplete>
    <div v-if="productVisible">
      <product-module ref="productModule" :visible="productVisible" @close="closeProductDialog" />
    </div>
  </div>
</template>

<script>

import { selectProductByName } from '@/api/erp/product'
import ProductModule from '@/modules/productModule.vue'

export default {
  name: 'ProductQuery',
  components: { ProductModule },
  props: {
    value: {
      type: String,
      default: undefined
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      productVisible: false,
      productName: '',
      productId: this.value,
      loading: false
    }
  },
  methods: {
    init(productName) {
      this.productName = productName
    },
    resetQueryForm() {
      this.productName = ''
      this.productId = undefined
    },
    // 打开产品弹窗
    openProductDialog() {
      this.productVisible = true
      this.$nextTick(() => {
        this.$refs.productModule.doPage()
      })
    },
    // 关闭产品弹窗
    closeProductDialog(row) {
      if (row) {
        this.productName = row.productName
        this.$emit('choose', row)
      }
      this.productVisible = false
    },
    // 产品选中
    handleSelectProduct(row) {
      if (row) {
        this.productName = row.productName
        this.$emit('choose', row)
      }
    },
    selectProductList(query, callback) {
      this.loading = true
      selectProductByName({ productName: query }).then(resp => {
        if (resp.success) {
          callback(resp.data)
        }
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
<style scoped>

</style>
